using CMS.Application.common.Interface;
using CMS.Application.Common.Interface;
using CMS.Application.RequestDto;
using CMS.Domain.Entity;
using Microsoft.AspNetCore.Mvc;

namespace CMS.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class FilesController : ControllerBase
    {
        private readonly IRepository<Blog> _blog;
        private readonly IRepository<Avatar> _avatar;
        private readonly IRepository<Users> _user;
        private readonly IRepository<BlogAllText> _blogalltext;
        private readonly IFileUploadService _FileUploadService;

        public FilesController(IRepository<Users> user,IFileUploadService FileUploadService, IRepository<Blog> blog, IRepository<Avatar> avatar, IRepository<BlogAllText> blogalltext)
        {
            _blog = blog;
            _avatar = avatar;
            _blogalltext = blogalltext;
            _FileUploadService=FileUploadService;
            _user=user;
        }


        /// <summary>
        /// 添加博文
        /// </summary>
        /// <param name="AddBlog"></param>
        /// <returns></returns>
        [HttpPost("/Files")]
        public async Task<object> AddBlog(FileDto fileDto)
        {

            // new一个Guid
            Guid Guid = System.Guid.NewGuid();


            //用作者id查询头像
            var userTable = await _user.GetByIdAsync(fileDto.AuthorId);


            // new一个实例，因为不晓得substring会不会改变原本的字符串所有我写在这上面
            var blogalltext = new BlogAllText
            {

                BlogId = Guid,

                BlogContent = fileDto.BlogContent
            };

            var BlogSomeText = fileDto.BlogContent;


            if (fileDto.BlogContent.Length >= 20)
            {


                // 截取文章的预览内容
                BlogSomeText = BlogSomeText.Substring(0, 20);//这个应该会有点问题将就着用


            }
 

            //new一个实体
            var file = new Blog
            {

                BlogId = Guid,
                AuthorId = fileDto.AuthorId,
                BlogTitle = fileDto.BlogTitle,
                BlogContent = BlogSomeText,
                AuthorAvatar = userTable.AvatarId

            };

            try
            {
                await _blog.AddAsync(file);
                await _blogalltext.AddAsync(blogalltext);
                return new
                {

                    code = "400",

                    data = "",

                    msg = "添加成功"

                };
            }
            catch
            {
                return new
                {

                    code = "400",

                    data = "",

                    msg = "添加失败"

                };
            }




        }

    }
}